<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="网点号" prop="regCode">
        <el-input
          v-model="queryParams.regCode"
          placeholder="请输入网点号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网点名称" prop="regName">
        <el-input
          v-model="queryParams.regName"
          placeholder="请输入网点名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址名称" prop="cityName">
        <el-input
          v-model="queryParams.cityName"
          placeholder="请输入地址名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="城市" prop="regCityId">
        <el-select
          v-model="queryParams.regCityId"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in cityList"
            :key="item.id"
            :label="item.cityName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:regBranch:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="regList">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="网点号" align="center" prop="regCode" />
      <el-table-column label="网点名称" align="center" prop="regName" />
      <el-table-column label="地址名称" align="center" prop="cityName" />
      <el-table-column label="是否限制  " align="center" prop="isStatus">
        <template slot-scope="scope">
          <el-tag
            effect="dark"
            size="mini"
            type="success"
            v-if="scope.row.isStatus === 1"
            >是</el-tag
          >
          <el-tag
            effect="dark"
            size="mini"
            type="danger"
            v-if="scope.row.isStatus === 0"
            >否</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="行政区划代码" align="center" prop="areaCode" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:regBranch:edit']"
            >修改</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mall:banner:remove']"
            >删除</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            @click="handleDownMallQrCode(scope.row)"
            v-hasPermi="['mall:regBranch:downMallQrCode']"
            >下载网点商城码</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商城首页轮播图对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="网点号" prop="regCode">
              <el-input v-model="form.regCode" placeholder="请输入网点号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网点名称" prop="regName">
              <el-input v-model="form.regName" placeholder="请输入网点名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="城市" prop="regCityId">
              <el-select
                v-model="form.regCityId"
                placeholder="请选择"
                @change="handleCityChange"
              >
                <el-option
                  v-for="item in cityList"
                  :key="item.id"
                  :label="item.cityName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 是否限制 -->
            <el-form-item label="地址名称" prop="cityName">
              <el-input v-model="form.cityName" placeholder="请输入地址名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 是否限制 -->
            <el-form-item label="是否限制" prop="isStatus">
              <el-radio-group v-model="form.isStatus">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 下载网点商城码对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="openDown"
      width="500px"
      append-to-body
    >
      <el-form ref="formDown" :model="formDown" label-width="100px">
        <el-form-item label="商户号" prop="merchantAccount">
          <el-input
            v-model="formDown.merchantAccount"
            placeholder="请输入商户号"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormDown" :loading="btnLoad"
          >确 定</el-button
        >
        <el-button @click="openDown = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBanner,
  getBanner,
  delBanner,
  addBanner,
  updateBanner,
  showBankBannerProduct,
  changeUpdateIsShelf,
  tagList,
  brandListNew,
  showMallAllProduct,
} from "@/api/system/banner";
import {
  regList,
  cityList,
  addRegBranch,
  updateRegBranch,
  getRegBranch,
  downMallQrCode,
} from "@/api/mallGuan/regBranch";
import { getToken } from "@/utils/auth";
export default {
  name: "RegBranch",
  data() {
    return {
      selectedProductList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      fileList: [],
      // 总条数
      total: 0,
      // 商城首页轮播图表格数据
      regList: [],
      // 轮播图位置列表
      positionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 城市列表
      cityList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bannerName: null,
      },
      // 是否显示下载网点商城码弹出层
      openDown: false,
      // 下载网点商城码参数
      formDown: {
        merchantAccount: null,
      },
      // 下载网点商城码按钮加载
      btnLoad: false,
      // 表单参数
      form: {
        regCode: null,
        regName: null,
        cityName: null,
        isStatus: null,
        areaCode: null,
      },

      // 表单校验
      rules: {
        regCode: [{ required: true, message: "请输入网点号", trigger: "blur" }],
        regName: [
          { required: true, message: "请输入网点名称", trigger: "blur" },
        ],
        cityName: [
          { required: true, message: "请输入地址名称", trigger: "blur" },
        ],
        isStatus: [
          { required: true, message: "请选择是否限制", trigger: "blur" },
        ],

        regCityId: [{ required: true, message: "请选择城市", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
    this.getCityList();
  },
  methods: {
    handleDownMallQrCode(row) {
      const { id, regName } = row;
      this.openDown = true;
      this.title = "下载网点商城码";
      this.formDown = {
        merchantAccount: null,
        regBranchId: id,
        mallId: 37,
        regName: regName,
      };
    },
    submitFormDown() {
      this.btnLoad = true;
      this.$refs["formDown"].validate((valid) => {
        if (valid) {
          downMallQrCode(this.formDown)
            .then((response) => {
              // this.$modal.msgSuccess("下载成功");
              this.openDown = false;
              // this.downloadImage(response.msg);
              const link = document.createElement("a");
              link.href = response.msg;
              link.download =
                this.formDown.regName + "_" + new Date().getTime() + ".png";
              link.click();
              this.btnLoad = false;
            })
            .catch(() => {
              this.btnLoad = false;
            });
        }
      });
    },
    // async downloadImage(url) {
    //   const filename = "网点商城码.png";

    //   try {
    //     const response = await fetch(url, {
    //       // 如果需要登录，带上 token
    //       headers: {
    //         Authorization: "Bearer " + getToken(), // 可选
    //       },
    //     });

    //     if (!response.ok) throw new Error("下载失败");

    //     const blob = await response.blob();
    //     const link = document.createElement("a");
    //     link.href = URL.createObjectURL(blob);
    //     link.download = filename;
    //     link.click();
    //     URL.revokeObjectURL(link.href); // 释放内存
    //   } catch (error) {
    //     console.error("下载失败:", error);
    //     alert("下载失败，请检查网络或权限");
    //   }
    // },

    handleCityChange(val) {
      const { areaCode } = this.cityList.find((item) => item.id === val);
      console.log(areaCode);
      this.form.areaCode = areaCode;
    },

    getCityList() {
      cityList().then((response) => {
        this.cityList = response.data;
      });
    },
    /** 查询商城首页轮播图列表 */
    getList() {
      this.loading = true;
      regList(this.queryParams).then((response) => {
        this.regList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 商家状态修改
    handleStatusChange(row) {
      console.log(row);
      const { id, isShelf } = row;
      let text = row.isShelf == 1 ? "上架" : "下架";
      this.$modal
        .confirm("确认要" + text + "" + row.bannerName + "吗？")
        .then(function () {
          return changeUpdateIsShelf({ id, isShelf });
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.isShelf = row.isShelf == 1 ? 0 : 1;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        regCode: null,
        regName: null,
        cityName: null,
        isStatus: null,
        areaCode: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加网点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRegBranch(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改网点";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateRegBranch(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegBranch(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商城首页轮播图编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBanner(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "banner/export",
        {
          ...this.queryParams,
        },
        `banner_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="less">
.el-radio {
  margin-right: 20px;
}
.img {
  width: 80px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  border: 1px dashed #ccc;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.image {
  width: 60px;
}
.image {
}
</style>
